<template>
  <div>
    <div>
      <el-divider />
      <el-row>
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="form.taskName"
            placeholder="请输入任务名称"
            style="width: 204px"
            :disabled="processStep < form.publishStauts"
          />
        </el-form-item>
        <el-form-item label="脚本选择方式" prop="scriptSelectType">
          <el-radio-group v-model="form.scriptSelectType" @change="scriptSelectTypeChange">
            <el-radio-button label="onlineDb">直连</el-radio-button>
            <el-radio-button label="exportImport" disabled="">导入</el-radio-button>
            <el-upload
              ref="uploadExcel"
              style="float: left"
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              multiple
              :show-file-list="false"
              :limit="3"
              :file-list="fileList"
            />
          </el-radio-group>
        </el-form-item>
      </el-row>
      <!-- <el-row v-if="form.scriptSelectType === 'onlineDb'">
        <el-form-item label="源/目标服务器" prop="sourceCode">
          <el-select v-model="form.sourceCode" placeholder="请选择" :disabled="processStep < form.publishStauts" @change="dataSourceConnChange">
            <el-option
              v-for="item in sourceConnList"
              :key="item.pkId"
              :label="item.sourceName"
              :value="item.pkId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="源/目标库" prop="dbName">
          <el-select v-model="form.dbName" placeholder="请选择" :disabled="processStep < form.publishStauts">
            <el-option v-for="dbName in sourceDatabaseList" :key="dbName" :label="dbName" :value="dbName" />
          </el-select>
        </el-form-item>
        <el-button
          class="bordered-button"
          :disabled="processStep < form.publishStauts"
          size="medium"
          type="text"
          @click="showScripList"
        >展示当前库下最新的脚本清单
        </el-button>
      </el-row> -->
      <el-row>
        <el-form-item label="业务流程" prop="businessPkId">
          <el-select v-model="form.businessPkId" placeholder="请选择" :disabled="processStep < form.publishStauts">
            <el-option
              v-for="item in businessList"
              :key="item.pkId"
              :label="item.processName"
              :value="item.pkId"
            />
          </el-select>
        </el-form-item>
        <el-button
          class="bordered-button"
          :disabled="processStep < form.publishStauts"
          size="medium"
          type="text"
          @click="showScripList"
        >展示当前库下最新的脚本清单
        </el-button>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="8">
          <el-input v-model.trim="queryName" clearable placeholder="请输入脚本名称" />
        </el-col>
        <el-button
          class="filter-item"
          size="mini"
          style="margin-left: 5px"
          type="success"
          icon="el-icon-search"
          @click="toQuery"
        >搜索
        </el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置
        </el-button>
        <el-button class="filter-item" type="danger" icon="el-icon-delete" size="mini" :disabled="processStep < form.publishStauts" @click="removeTestScript">删除
        </el-button>
      </el-row>
      <el-table :data="form.publishScriptList" border max-height="240" @selection-change="testScriptHandleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column prop="scriptName" label="脚本名称" />
      </el-table>
    </div>

    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="isSelectScriptFlag"
      title="选择发布脚本"
      width="1000px"
    >
      <div>
        <el-transfer
          v-if="isSelectScriptFlag"
          v-model="selectScriptList"
          filterable
          :titles="['所有脚本', '已选择脚本']"
          :format="{ noChecked: '${total}', hasChecked: '${checked}/${total}'}"
          :props="{key: 'pkId', label: 'convertFileName'}"
          :data="scriptList"
        />
      </div>
      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center">
        <el-button type="primary" style="margin-right: 30px" @click="submitSelectScript">同意</el-button>
        <el-button @click="isSelectScriptFlag=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataSourceConnApi from '@/api/metadata/dataSource'
import convertScriptListApi from '@/api/script/transfer/script-convert-target-list'
import publishBusinessApi from '@/api/golive/alibabaPublish/publishBusiness'

export default {
  name: 'ScriptConvertList',
  model: {
    prop: 'form',
    event: 'changes'
  },
  props: {
    form: {
      required: true,
      type: Object
    }
  },
  data() {
    return {
      processStep: 0,
      fileList: [],
      isSelectScriptFlag: false,
      selectScriptList: [],
      scriptList: [],
      sourceConnList: [],
      sourceDatabaseList: [],
      businessList: [],
      queryName: null,
      selectTestScriptName: [],
      tempTestScriptList: []
    }
  },
  created() {
    this.initData()
  },
  methods: {
    checkProcessStep() {
      if (this.processStep <= this.form.publishStauts) {
        return true
      } else {
        return false
      }
    },
    scriptSelectTypeChange(val) {
      if (val === 'exportImport') {
        this.$refs['uploadExcel'].$refs['upload-inner'].handleClick()
      }
    },
    initData() {
      const param = { size: 500, status: 'ENABLE' }
      dataSourceConnApi.findListByPage(param).then(data => {
        this.sourceConnList = data.content
      }).catch(() => {
        this.crud.notify('获取源/目标服务器失败！', 'error')
      })
      publishBusinessApi.findListByPage(param).then(data => {
        this.businessList = data.content
      }).catch(() => {
        this.crud.notify('获取业务流程失败！', 'error')
      })
    },
    dataSourceConnChange(sourceCode) {
      dataSourceConnApi.schemas(sourceCode).then(res => {
        this.sourceDatabaseList = res
      })
    },
    showScripList() {
      this.resetQuery()
      const param = {
        size: 500,
        emptyTestStatus: 'SUCCESS',
        sourceConnPkId: this.form.sourceCode,
        database: this.form.dbName
      }
      convertScriptListApi.findLatestSuccess(param).then(data => {
        this.scriptList = data.content
        this.initselectScriptList()
        this.isSelectScriptFlag = true
      }).catch(() => {
        this.crud.notify('获取转换脚本清单失败！', 'error')
      })
    },
    initselectScriptList() {
      this.selectScriptList = []
      this.scriptList.forEach(item => {
        this.form.publishScriptList.forEach(item2 => {
          if (item2.scriptConvertListPkId === item.pkId) {
            this.selectScriptList.push(item.pkId)
          }
        })
      })
    },
    toQuery() {
      if (this.queryName === undefined || this.queryName === null || this.queryName === '') {
        this.resetQuery()
      } else {
        this.tempTestScriptList = JSON.parse(JSON.stringify(this.form.publishScriptList))
        this.form.publishScriptList = this.form.publishScriptList.filter((item) => {
          return item.scriptName.toUpperCase().includes(this.queryName.toUpperCase())
        })
      }
    },
    resetQuery() {
      this.queryName = null
      if (this.tempTestScriptList !== undefined && this.tempTestScriptList.length > 0) {
        this.form.publishScriptList = JSON.parse(JSON.stringify(this.tempTestScriptList))
        this.tempTestScriptList = []
      }
    },
    // 记录选择的测试脚本
    testScriptHandleSelectionChange(val) {
      this.selectTestScriptName = []
      val.forEach(item => {
        this.selectTestScriptName.push(item.scriptConvertListPkId)
      })
    },
    // 删除测试脚本
    removeTestScript() {
      this.selectTestScriptName.forEach(removeId => {
        this.form.publishScriptList.forEach((item, index) => {
          if (removeId === item.scriptConvertListPkId) {
            this.form.publishScriptList.splice(index, 1)
          }
        })
        this.selectScriptList.forEach((id, index) => {
          if (removeId === id) {
            this.selectScriptList.splice(index, 1)
          }
        })
      })
    },
    submitSelectScript() {
      const scriptConvertListPkIds = this.form.publishScriptList.map(item => {
        return item.scriptConvertListPkId
      })
      this.isSelectScriptFlag = false
      this.scriptList.forEach(item => {
        if (this.selectScriptList.includes(item.pkId) && !scriptConvertListPkIds.includes(item.pkId)) {
          const data = { pkId: null, taskPkId: null, scriptConvertListPkId: item.pkId, scriptName: item.convertFileName, status: 'TODO' }
          this.form.publishScriptList.push(data)
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-transfer-panel {
  width: 400px !important;
}

::v-deep .bordered-button {
  border: #92dab3 2px;
}

::v-deep .el-transfer__buttons button {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

::v-deep .el-transfer__buttons button:last-child {
  margin-left: 0px;
}
</style>
